<template>
  <div class="read"  v-infinite-scroll="loadMore"
       infinite-scroll-disabled="loading"
       infinite-scroll-distance="20">

    <chapters v-if="chapter.title"   :chapter="chapter" :infinite="true"></chapters>
    <p class="none" v-else>暂无数据</p>
    <mt-button @click="loadMore">Load more ...</mt-button>
  </div>
</template>

<script>
  import Chapters  from './Chapters.vue';
  import fetch from '@/utils/fetch';
  export default {
    name: "R",
    components:{
      chapters: Chapters
    },
    data(){
      return {
        chapter: {},
        totalCached: 5,
        cached: [],
        tempChapter:{},
        cacheUrl: '',
        loading: false,
      }
    },
    created(){
      if(this.$route.query.url){
        this.getChapter(this.$route.query.url)
      }
    },
    activated(){
      if(this.$route.query.url){
        this.chapter = {}
        this.getChapter(this.$route.query.url)
      }else {
        this.chapter = this.tempChapter
      }
    },
    deactivated(){
      this.chapter = {}
    },
    watch:{
      cacheUrl(nv){
        if(nv&&this.totalCached>0){
          fetch.get(`api/novel?curl=${nv}`).then(res=>{
            const next = res.data;
            next.url = nv;
            this.cacheUrl = res.data.next;
            this.totalCached --;
            this.cached.push(next)
          })
        }
        if(this.totalCached === 0){
          this.totalCached = 5
        }
      },
    },
    methods:{
      loadMore(){
        if(this.chapter.title && this.cached.length>0){
          const next = this.cached.shift();
          this.tempChapter = next;
          this.chapter.content += next.content
          this.$router.push(`/reader/r?url=${next.url}`)
          for(let key in this.chapter){
            if(key !== 'content'){
              this.chapter[key] = next[key]
            }
          }
          if(this.cached.length ===0 ){
            this.getChapter(next.next)
          }
        }
      },
      getChapter(url){
        fetch.get(`api/novel?curl=${url}`).then(res=>{
          if(this.chapter.content){
            for(let key in res.data){
              if(key !== 'content'){
                this.chapter[key] = res.data[key]
              }
            }
          }else {
            this.chapter = res.data
          }
          this.cacheUrl = res.data.next;
          this.cached = [];
        })
      },
    }

  }
</script>

<style scoped>
</style>
